{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7ff0dfa3",
   "metadata": {},
   "source": [
    "Installing (updating) the following libraries for your Sagemaker\n",
    "instance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a3090c7e",
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install .. # installing d2l\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fdaad6d5",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# 文本预处理\n",
    ":label:`sec_text_preprocessing`\n",
    "\n",
    "对于序列数据处理问题，我们在 :numref:`sec_sequence`中\n",
    "评估了所需的统计工具和预测时面临的挑战。\n",
    "这样的数据存在许多种形式，文本是最常见例子之一。\n",
    "例如，一篇文章可以被简单地看作一串单词序列，甚至是一串字符序列。\n",
    "本节中，我们将解析文本的常见预处理步骤。\n",
    "这些步骤通常包括：\n",
    "\n",
    "1. 将文本作为字符串加载到内存中。\n",
    "1. 将字符串拆分为词元（如单词和字符）。\n",
    "1. 建立一个词表，将拆分的词元映射到数字索引。\n",
    "1. 将文本转换为数字索引序列，方便模型操作。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "bb8907ca",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:02:24.243885Z",
     "iopub.status.busy": "2023-08-18T07:02:24.243343Z",
     "iopub.status.idle": "2023-08-18T07:02:26.213654Z",
     "shell.execute_reply": "2023-08-18T07:02:26.212745Z"
    },
    "origin_pos": 2,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "import collections\n",
    "import re\n",
    "from d2l import torch as d2l"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e987bf4c",
   "metadata": {
    "origin_pos": 5
   },
   "source": [
    "## 读取数据集\n",
    "\n",
    "首先，我们从H.G.Well的[时光机器](https://www.gutenberg.org/ebooks/35)中加载文本。\n",
    "这是一个相当小的语料库，只有30000多个单词，但足够我们小试牛刀，\n",
    "而现实中的文档集合可能会包含数十亿个单词。\n",
    "下面的函数(**将数据集读取到由多条文本行组成的列表中**)，其中每条文本行都是一个字符串。\n",
    "为简单起见，我们在这里忽略了标点符号和字母大写。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ac0f9f0d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:02:26.218338Z",
     "iopub.status.busy": "2023-08-18T07:02:26.217685Z",
     "iopub.status.idle": "2023-08-18T07:02:26.304928Z",
     "shell.execute_reply": "2023-08-18T07:02:26.304151Z"
    },
    "origin_pos": 6,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Downloading ../data/timemachine.txt from http://d2l-data.s3-accelerate.amazonaws.com/timemachine.txt...\n",
      "# 文本总行数: 3221\n",
      "the time machine by h g wells\n",
      "twinkled and his usually pale face was flushed and animated the\n"
     ]
    }
   ],
   "source": [
    "#@save\n",
    "d2l.DATA_HUB['time_machine'] = (d2l.DATA_URL + 'timemachine.txt',\n",
    "                                '090b5e7e70c295757f55df93cb0a180b9691891a')\n",
    "\n",
    "def read_time_machine():  #@save\n",
    "    \"\"\"将时间机器数据集加载到文本行的列表中\"\"\"\n",
    "    with open(d2l.download('time_machine'), 'r') as f:\n",
    "        lines = f.readlines()\n",
    "    return [re.sub('[^A-Za-z]+', ' ', line).strip().lower() for line in lines]\n",
    "\n",
    "lines = read_time_machine()\n",
    "print(f'# 文本总行数: {len(lines)}')\n",
    "print(lines[0])\n",
    "print(lines[10])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c34664d1",
   "metadata": {
    "origin_pos": 7
   },
   "source": [
    "## 词元化\n",
    "\n",
    "下面的`tokenize`函数将文本行列表（`lines`）作为输入，\n",
    "列表中的每个元素是一个文本序列（如一条文本行）。\n",
    "[**每个文本序列又被拆分成一个词元列表**]，*词元*（token）是文本的基本单位。\n",
    "最后，返回一个由词元列表组成的列表，其中的每个词元都是一个字符串（string）。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "afd6a9df",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:02:26.308604Z",
     "iopub.status.busy": "2023-08-18T07:02:26.308048Z",
     "iopub.status.idle": "2023-08-18T07:02:26.317083Z",
     "shell.execute_reply": "2023-08-18T07:02:26.316264Z"
    },
    "origin_pos": 8,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['the', 'time', 'machine', 'by', 'h', 'g', 'wells']\n",
      "[]\n",
      "[]\n",
      "[]\n",
      "[]\n",
      "['i']\n",
      "[]\n",
      "[]\n",
      "['the', 'time', 'traveller', 'for', 'so', 'it', 'will', 'be', 'convenient', 'to', 'speak', 'of', 'him']\n",
      "['was', 'expounding', 'a', 'recondite', 'matter', 'to', 'us', 'his', 'grey', 'eyes', 'shone', 'and']\n",
      "['twinkled', 'and', 'his', 'usually', 'pale', 'face', 'was', 'flushed', 'and', 'animated', 'the']\n"
     ]
    }
   ],
   "source": [
    "def tokenize(lines, token='word'):  #@save\n",
    "    \"\"\"将文本行拆分为单词或字符词元\"\"\"\n",
    "    if token == 'word':\n",
    "        return [line.split() for line in lines]\n",
    "    elif token == 'char':\n",
    "        return [list(line) for line in lines]\n",
    "    else:\n",
    "        print('错误：未知词元类型：' + token)\n",
    "\n",
    "tokens = tokenize(lines)\n",
    "for i in range(11):\n",
    "    print(tokens[i])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e61c06e8",
   "metadata": {
    "origin_pos": 9
   },
   "source": [
    "## 词表\n",
    "\n",
    "词元的类型是字符串，而模型需要的输入是数字，因此这种类型不方便模型使用。\n",
    "现在，让我们[**构建一个字典，通常也叫做*词表*（vocabulary），\n",
    "用来将字符串类型的词元映射到从$0$开始的数字索引中**]。\n",
    "我们先将训练集中的所有文档合并在一起，对它们的唯一词元进行统计，\n",
    "得到的统计结果称之为*语料*（corpus）。\n",
    "然后根据每个唯一词元的出现频率，为其分配一个数字索引。\n",
    "很少出现的词元通常被移除，这可以降低复杂性。\n",
    "另外，语料库中不存在或已删除的任何词元都将映射到一个特定的未知词元“&lt;unk&gt;”。\n",
    "我们可以选择增加一个列表，用于保存那些被保留的词元，\n",
    "例如：填充词元（“&lt;pad&gt;”）；\n",
    "序列开始词元（“&lt;bos&gt;”）；\n",
    "序列结束词元（“&lt;eos&gt;”）。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "16db7dad",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:02:26.320587Z",
     "iopub.status.busy": "2023-08-18T07:02:26.320050Z",
     "iopub.status.idle": "2023-08-18T07:02:26.330519Z",
     "shell.execute_reply": "2023-08-18T07:02:26.329736Z"
    },
    "origin_pos": 10,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "class Vocab:  #@save\n",
    "    \"\"\"文本词表\"\"\"\n",
    "    def __init__(self, tokens=None, min_freq=0, reserved_tokens=None):\n",
    "        if tokens is None:\n",
    "            tokens = []\n",
    "        if reserved_tokens is None:\n",
    "            reserved_tokens = []\n",
    "        # 按出现频率排序\n",
    "        counter = count_corpus(tokens)\n",
    "        self._token_freqs = sorted(counter.items(), key=lambda x: x[1],\n",
    "                                   reverse=True)\n",
    "        # 未知词元的索引为0\n",
    "        self.idx_to_token = ['<unk>'] + reserved_tokens\n",
    "        self.token_to_idx = {token: idx\n",
    "                             for idx, token in enumerate(self.idx_to_token)}\n",
    "        for token, freq in self._token_freqs:\n",
    "            if freq < min_freq:\n",
    "                break\n",
    "            if token not in self.token_to_idx:\n",
    "                self.idx_to_token.append(token)\n",
    "                self.token_to_idx[token] = len(self.idx_to_token) - 1\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.idx_to_token)\n",
    "\n",
    "    def __getitem__(self, tokens):\n",
    "        if not isinstance(tokens, (list, tuple)):\n",
    "            return self.token_to_idx.get(tokens, self.unk)\n",
    "        return [self.__getitem__(token) for token in tokens]\n",
    "\n",
    "    def to_tokens(self, indices):\n",
    "        if not isinstance(indices, (list, tuple)):\n",
    "            return self.idx_to_token[indices]\n",
    "        return [self.idx_to_token[index] for index in indices]\n",
    "\n",
    "    @property\n",
    "    def unk(self):  # 未知词元的索引为0\n",
    "        return 0\n",
    "\n",
    "    @property\n",
    "    def token_freqs(self):\n",
    "        return self._token_freqs\n",
    "\n",
    "def count_corpus(tokens):  #@save\n",
    "    \"\"\"统计词元的频率\"\"\"\n",
    "    # 这里的tokens是1D列表或2D列表\n",
    "    if len(tokens) == 0 or isinstance(tokens[0], list):\n",
    "        # 将词元列表展平成一个列表\n",
    "        tokens = [token for line in tokens for token in line]\n",
    "    return collections.Counter(tokens)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7fde2e0",
   "metadata": {
    "origin_pos": 11
   },
   "source": [
    "我们首先使用时光机器数据集作为语料库来[**构建词表**]，然后打印前几个高频词元及其索引。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "1501d478",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:02:26.333942Z",
     "iopub.status.busy": "2023-08-18T07:02:26.333382Z",
     "iopub.status.idle": "2023-08-18T07:02:26.346927Z",
     "shell.execute_reply": "2023-08-18T07:02:26.346182Z"
    },
    "origin_pos": 12,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('<unk>', 0), ('the', 1), ('i', 2), ('and', 3), ('of', 4), ('a', 5), ('to', 6), ('was', 7), ('in', 8), ('that', 9)]\n"
     ]
    }
   ],
   "source": [
    "vocab = Vocab(tokens)\n",
    "print(list(vocab.token_to_idx.items())[:10])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce7b78a3",
   "metadata": {
    "origin_pos": 13
   },
   "source": [
    "现在，我们可以(**将每一条文本行转换成一个数字索引列表**)。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f0244f09",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:02:26.350343Z",
     "iopub.status.busy": "2023-08-18T07:02:26.349779Z",
     "iopub.status.idle": "2023-08-18T07:02:26.354215Z",
     "shell.execute_reply": "2023-08-18T07:02:26.353468Z"
    },
    "origin_pos": 14,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "文本: ['the', 'time', 'machine', 'by', 'h', 'g', 'wells']\n",
      "索引: [1, 19, 50, 40, 2183, 2184, 400]\n",
      "文本: ['twinkled', 'and', 'his', 'usually', 'pale', 'face', 'was', 'flushed', 'and', 'animated', 'the']\n",
      "索引: [2186, 3, 25, 1044, 362, 113, 7, 1421, 3, 1045, 1]\n"
     ]
    }
   ],
   "source": [
    "for i in [0, 10]:\n",
    "    print('文本:', tokens[i])\n",
    "    print('索引:', vocab[tokens[i]])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e84c1a2a",
   "metadata": {
    "origin_pos": 15
   },
   "source": [
    "## 整合所有功能\n",
    "\n",
    "在使用上述函数时，我们[**将所有功能打包到`load_corpus_time_machine`函数中**]，\n",
    "该函数返回`corpus`（词元索引列表）和`vocab`（时光机器语料库的词表）。\n",
    "我们在这里所做的改变是：\n",
    "\n",
    "1. 为了简化后面章节中的训练，我们使用字符（而不是单词）实现文本词元化；\n",
    "1. 时光机器数据集中的每个文本行不一定是一个句子或一个段落，还可能是一个单词，因此返回的`corpus`仅处理为单个列表，而不是使用多词元列表构成的一个列表。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "578ed76f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:02:26.357414Z",
     "iopub.status.busy": "2023-08-18T07:02:26.357141Z",
     "iopub.status.idle": "2023-08-18T07:02:26.470812Z",
     "shell.execute_reply": "2023-08-18T07:02:26.470008Z"
    },
    "origin_pos": 16,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(170580, 28)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def load_corpus_time_machine(max_tokens=-1):  #@save\n",
    "    \"\"\"返回时光机器数据集的词元索引列表和词表\"\"\"\n",
    "    lines = read_time_machine()\n",
    "    tokens = tokenize(lines, 'char')\n",
    "    vocab = Vocab(tokens)\n",
    "    # 因为时光机器数据集中的每个文本行不一定是一个句子或一个段落，\n",
    "    # 所以将所有文本行展平到一个列表中\n",
    "    corpus = [vocab[token] for line in tokens for token in line]\n",
    "    if max_tokens > 0:\n",
    "        corpus = corpus[:max_tokens]\n",
    "    return corpus, vocab\n",
    "\n",
    "corpus, vocab = load_corpus_time_machine()\n",
    "len(corpus), len(vocab)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "28620a4d",
   "metadata": {
    "origin_pos": 17
   },
   "source": [
    "## 小结\n",
    "\n",
    "* 文本是序列数据的一种最常见的形式之一。\n",
    "* 为了对文本进行预处理，我们通常将文本拆分为词元，构建词表将词元字符串映射为数字索引，并将文本数据转换为词元索引以供模型操作。\n",
    "\n",
    "## 练习\n",
    "\n",
    "1. 词元化是一个关键的预处理步骤，它因语言而异。尝试找到另外三种常用的词元化文本的方法。\n",
    "1. 在本节的实验中，将文本词元为单词和更改`Vocab`实例的`min_freq`参数。这对词表大小有何影响？\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17f3b26f",
   "metadata": {
    "origin_pos": 19,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/2094)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "conda_pytorch_p36",
   "name": "conda_pytorch_p36"
  },
  "language_info": {
   "name": "python"
  },
  "required_libs": []
 },
 "nbformat": 4,
 "nbformat_minor": 5
}